import psycopg2
import psycopg2.extras
import sys
from shapely.geometry import box
from shapely.wkt import dumps, loads
import gdal
from gdalconst import *
import os
import constant

#select mod04 query
mod04_query = "SELECT filename, path, ST_AsText(corner) as corner FROM satorgmod04 where aqstime > '2014-01-01 00:00:00'::timestamp and aqstime < '2014-09-14 00:00:00'::timestamp"
myd04_query = "SELECT filename, path, ST_AsText(corner) as corner FROM satorgmyd04"
		
#Resample mod04		
def resample_mod04(query,resx,resy):
	aod_format = "_DT_10km.tif"
	aod_type_format = "_AT_10km.tif"
	org_folder = "public/SatOrgMOD04"
	resample_folder= "apom/Resample/SatResampMOD04"
	

	#band name
	aod_band = '":mod04:Optical_Depth_Land_And_Ocean'
	aodtype_band = '":mod04:Aerosol_Type_Land'
	con = None
	try:
		# Connect to DB
		con = psycopg2.connect(host=constant.host, database = constant.database, user= constant.user, password=constant.password) 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		
		#Query to satorgmod04 table
		cur.execute(query)
		rows = cur.fetchall()
	
		for row in rows:
			
			filename = row["filename"].strip()
			path = row["path"].strip()
			path = path[:-1]
			
			# row["corner"]: toa do 4 goc WKT
			# loads(): cua thu vien shapely dua dang WKT ve dang object
			corner = loads(row["corner"])
			
			# kiem tra anh hdf co chua viet nam hoac giao voi viet nam k
			if corner.within(constant.vietnam_bounds) or corner.intersects(constant.vietnam_bounds):
			
				#folder_path: /var/www/html/
				#path: fimo/public/SatOrgMOD04/2014/MOD04_L2.A2014164.0330.051.2014164132730
				#filename:MOD04_L2.A2014164.0330.051.2014164132730.hdf
				
				path = os.path.join(constant.folder_path, path)
				
				inputfilename = path +"/"+filename
				#inputfilename = path + filename

				# AOD input
				aod_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + aod_band
				
				#AOD out put: thay ten thu muc SatResampleMOD04 thanh SatResampMOD04
				aod_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + aod_format)
				
				#check folder exist
				if not os.path.exists(os.path.dirname(aod_output_file)):
					os.makedirs(os.path.dirname(aod_output_file))
				#execute gdal_warp command
				re_griding(aod_input_file, resx, resy, aod_output_file)
				
				#AOD type input
				aodtype_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + aodtype_band
				
				#AOD type out put: Thay ten thu muc	SatResampleMOD04 thanh SatResampMOD04
				aodtype_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + aod_type_format)
				#if not os.path.exists(os.path.dirname(aodtype_output_file)):
				#	os.makedirs(os.path.dirname(aodtype_output_file))

				re_griding(aodtype_input_file, resx, resy, aodtype_output_file)
	except psycopg2.DatabaseError, e:
		print 'Error %s' % e    
		sys.exit(1)
	finally:
		if con:
			con.close()

#Resample myd04		
def regrid_myd04(query,resx,resy):
	aod_format = "_CB_10km.tif"
	aod_type_format = "_AT_10km.tif"
	org_folder = "public/SatOrgMYD04"
	resample_folder= "apom/Resample/SatResampMYD04"
	

	#band name
	aod_band = '":mod04:AOD_550_Dark_Target_Deep_Blue_Combined'
	aodtype_band = '":mod04:Aerosol_Type_Land'
	con = None
	try:
		# Connect to DB
		con = psycopg2.connect(host=constant.host, database = constant.database, user= constant.user, password=constant.password) 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		
		#Query to satorgmyd04 table
		cur.execute(query)
		rows = cur.fetchall()
	
		for row in rows:
			
			filename = row["filename"].strip()
			path = row["path"].strip()
			path = path[:-1]
			
			# row["corner"]: toa do 4 goc WKT
			# loads(): cua thu vien shapely dua dang WKT ve dang object
			corner = loads(row["corner"])
			
			# kiem tra anh hdf co chua viet nam hoac giao voi viet nam k
			if corner.within(constant.vietnam_bounds) or corner.intersects(constant.vietnam_bounds):
			
				#folder_path: /var/www/html/
				#path: fimo/public/SatOrgMYD04/2014/MYD04_L2.A2014164.0330.051.2014164132730
				#filename:MYD04_L2.A2014164.0330.051.2014164132730.hdf
				
				path = os.path.join(constant.folder_path, path)
				
				inputfilename = path +"/"+filename
				#inputfilename = path + filename

				# AOD input
				aod_input_file = 'HDF4_EOS:EOS_SWATH:"'+ inputfilename + aod_band
				
				#AOD out put: thay ten thu muc SatOrgMYD04 thanh SatResampMYD04
				aod_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + aod_format)
				
				#check folder exist
				if not os.path.exists(os.path.dirname(aod_output_file)):
					os.makedirs(os.path.dirname(aod_output_file))
				#execute gdal_warp command
				re_griding(aod_input_file, resx, resy, aod_output_file)
				
				#AOD type input
				aodtype_input_file = 'HDF4_EOS:EOS_SWATH:"'+inputfilename+ aodtype_band
				
				#AOD type out put: Thay ten thu muc	SatOrgMYD04 thanh SatResampMYD04
				aodtype_output_file = os.path.join(path.replace(org_folder,resample_folder), filename + aod_type_format)
			
				re_griding(aodtype_input_file, resx, resy, aodtype_output_file)
	except psycopg2.DatabaseError, e:
		print 'Error %s' % e    
		sys.exit(1)
	finally:
		if con:
			con.close()
			

def re_griding(inputfile, resx, resy, ouputfile):
		
	#convert hdf to tiff 
	#regrid_command = "gdalwarp -t_srs '+proj=longlat +datum=WGS84' -tps -ot Float32 -wt Float32  -srcnodata -9999 -dstnodata -9999 {0} {1}".format( inputfile, ouputfile)
	
	#resample command
	regrid_command = "gdalwarp -t_srs '+proj=longlat +datum=WGS84' -tps -ot Float32 -wt Float32 -te 100.1 6.4 111.8 25.6 -tr {0} {1} -r cubic -srcnodata -9999 -dstnodata -9999 -overwrite -multi {2} {3}"
	
	
	os.system(regrid_command.format(resx, resy, inputfile, ouputfile))

if __name__ == '__main__':
	resample_mod04(mod04_query, constant.res10x,constant.res10y)
	#regrid_myd04(myd04_query, constant.res10x,constant.res10y)
	